<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useMessage, NCheckboxGroup, NCheckbox, NInput, NButton, NGrid, NGi, NSpin } from 'naive-ui';
import { $t } from '@/locales';
import { zhCN, ProCard, createProForm } from 'pro-naive-ui';
import ConfigProvider from '../../ConfigProvider.vue';

import {
  fetchGetCheckboxList,
  fetchGetInputConfig,
  fetchSaveConfig
} from '@/service/api/erp';

interface CheckboxItem {
  optionKey: string;
  optionText: string;
  isChecked: boolean;
  description?: string;
}

interface InputConfigItem {
  inputDesc: string;
  inputPlaceholder: string;
  defaultValue: string;
}

const message = useMessage();
const submitting = ref(false);
const isLoading = ref(true);

const checkboxList = ref<CheckboxItem[]>([]);
const inputConfig = ref<InputConfigItem>({
  inputDesc: '',
  inputPlaceholder: '',
  defaultValue: ''
});
const checkedKeys = ref<string[]>([]);

const loadData = async () => {
  try {
    isLoading.value = true;
    const [checkboxRes, inputRes] = await Promise.all([
      fetchGetCheckboxList() as any,
      fetchGetInputConfig() as any
    ]);

    checkboxList.value = (checkboxRes.data || []) as CheckboxItem[];
    inputConfig.value = (inputRes.data || {
      inputDesc: '',
      inputPlaceholder: '',
      defaultValue: ''
    }) as InputConfigItem;

    checkedKeys.value = checkboxList.value
      .filter(item => item.isChecked)
      .map(item => item.optionKey);
  } catch (error) {
    message.error('数据加载异常，请刷新重试');
  } finally {
    isLoading.value = false;
  }
};

// ✅ 把 handleSave / handleReset 接入 form
const form = createProForm({
  initialValues: {},
  onSubmit: async () => {
    try {
      submitting.value = true;
      const saveParams = {
        checkedKeys: checkedKeys.value,
        inputValue: inputConfig.value.defaultValue
      };
      await fetchSaveConfig(saveParams);
      message.success('保存成功');
    } catch (error) {
      message.error('保存失败');
    } finally {
      submitting.value = false;
    }
  },
  onReset: () => {
    loadData();
    message.success('已重置为初始状态');
  }
});

onMounted(() => {
  loadData();
});
</script>

<template>
  <ConfigProvider :locale="zhCN">
    <ProForm :form="form" :loading="submitting">
      <ProCard :title="$t('page.system_erp.title')" :show-collapse="false">
        <template #header-extra>
          <NFlex gap="12px">
            <NButton attr-type="reset" :disabled="isLoading">
              {{ '重置' }}
            </NButton>
            <NButton type="primary" attr-type="submit" :loading="submitting">
              {{ '保存配置' }}
            </NButton>
          </NFlex>
        </template>

        <NSpin :show="isLoading" size="medium" style="min-height: 280px;">
          <NGrid cols="1" :y-gap="32">
            <!-- 复选框区域 -->
            <NGi>
              <div class="form-section">
                <h3 style="font-size: 16px; margin: 0; color: #333;">
                  {{ $t('page.system_erp.optionTitle') || '功能配置' }}
                </h3>
                <NCheckboxGroup v-model:value="checkedKeys">
                  <div v-for="item in checkboxList" :key="item.optionKey"
                    style="display: flex; align-items: flex-start; gap: 8px; margin-bottom: 8px;">
                    <NCheckbox :value="item.optionKey" />
                    <div>
                      <span style="font-size: 14px;">{{ item.optionText }}</span>
                      <p v-if="item.description" style="margin: 4px 0 0; font-size: 12px; color: #666;">
                        {{ item.description }}
                      </p>
                    </div>
                  </div>
                </NCheckboxGroup>
              </div>
            </NGi>

            <!-- 输入框区域 -->
            <NGi>
              <div class="form-section">
                <div style="display: flex; align-items: center; gap: 12px;">
                  <p style="margin: 0; font-size: 14px; color: #666; white-space: nowrap;">
                    {{ inputConfig.inputDesc }}
                  </p>
                  <NInput v-model:value="inputConfig.defaultValue" :placeholder="inputConfig.inputPlaceholder"
                    style="flex: 1; max-width: 500px;" />
                </div>
              </div>
            </NGi>
          </NGrid>
        </NSpin>
      </ProCard>
    </ProForm>
  </ConfigProvider>
</template>


<style scoped>
.erp-page {
  font-family: "Microsoft YaHei", Arial, sans-serif;
  background: #f5f7fa;
  min-height: calc(100vh - 160px);
  padding: 20px;
}

.form-section {
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}
</style>
